package com.dmz.proxy.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 安全拦截器
 */
@Component
@Slf4j
public class SecurityInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置安全头
        setSecurityHeaders(response);
        
        // 记录请求日志（可选）
        log.debug("Request: {} {} from {}", request.getMethod(), request.getRequestURI(), request.getRemoteAddr());
        
        return true;
    }
    
    /**
     * 设置安全相关的HTTP头
     */
    private void setSecurityHeaders(HttpServletResponse response) {
        // 防止MIME类型嗅探
        response.setHeader("X-Content-Type-Options", "nosniff");
        
        // 启用XSS保护
        response.setHeader("X-XSS-Protection", "1; mode=block");
        
        // 内容安全策略
        response.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'");
        
        // 防止点击劫持
        response.setHeader("X-Frame-Options", "DENY");
        
        // 禁用客户端缓存敏感数据
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
    }
}